package com.github.icloudpay.pay.core.service.pay.other.service;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.github.icloudpay.pay.core.entity.PayHelperUrlConfiguration;
import com.github.icloudpay.pay.core.feign.NettyFeign;
import com.github.icloudpay.pay.core.feign.PayChannelConfigFeign;
import com.github.icloudpay.pay.core.inter.PayObjectService;
import com.github.icloudpay.pay.core.mapper.PayHelperUrlConfigurationMapper;
import com.github.wxiaoqi.security.biz.common.admin.pay.request.OnlinePaymentRequest;
import com.github.wxiaoqi.security.biz.common.msg.BizResponseCode;
import com.github.wxiaoqi.security.cache.CacheProvider;

/**
 * 支付助手app支付
 * @author he
 */
@Service("payHelperPaymentService")
public class PayHelperPaymentService implements PayObjectService<OnlinePaymentRequest> {
	
	private static final Logger logger = LoggerFactory.getLogger(PayHelperPaymentService.class);
	
	@Autowired
	private PayChannelConfigFeign payChannelConfigFeign;
	@Autowired
	private PayHelperUrlConfigurationMapper payHelperUrlConfigurationMapper;
	@Autowired
	private NettyFeign nettyFeign;

	@Override
	public Map<String, Object> pay(OnlinePaymentRequest request) {
		
		logger.info("****************调用个人二维码支付接口开始*******************");

		Map<String, Object> responseMap = new HashMap<String, Object>();

		Map<String, Object> reqMap = new HashMap<String, Object>();
    	reqMap.put("platformId", request.getPlatformId());
    	reqMap.put("merchantId", request.getMerchantId());
    	reqMap.put("payChannelNo", request.getPayChannelNo());
		Map<String, Object> respMap = payChannelConfigFeign.query(reqMap);
        if(!(boolean) respMap.get("success")){
			responseMap.put("success", false);
			responseMap.put("code", BizResponseCode.PAYCHANNEL_CONFIGURATION_NOTEXIST.getCode());
			responseMap.put("message", BizResponseCode.PAYCHANNEL_CONFIGURATION_NOTEXIST.getMessage());
			return responseMap;
		}
        
        Map<String, Object> resultMap = new HashMap<String, Object>();
        PayHelperUrlConfiguration queryConfigurationInfo = null;
        
        //查询获取二维码地址
        //从redis中获取执行到第几条
        int num = 0;
        String numStr = CacheProvider.get("num");
        Map<String, Object> requestMap = new HashMap<String, Object>();
        requestMap.put("numberType", request.getExtra().get("payType"));
        if(StringUtils.isEmpty(numStr)){
        	//为空时赋初始值
        	num = 0;
        	requestMap.put("num", num);
    		queryConfigurationInfo = payHelperUrlConfigurationMapper.queryConfigurationInfo(requestMap);
    		//记录新的redis数据
    		CacheProvider.set("num", String.valueOf(0));
        }else{
        	//查询
        	PayHelperUrlConfiguration payHelperUrlConfiguration = new PayHelperUrlConfiguration();
        	payHelperUrlConfiguration.setPlatformId(request.getPlatformId());
        	payHelperUrlConfiguration.setTxStatus("00");//正常
        	payHelperUrlConfiguration.setNumberType((String) request.getExtra().get("payType"));
        	int selectCount = payHelperUrlConfigurationMapper.selectCount(payHelperUrlConfiguration);
        	Integer numInt = Integer.valueOf(numStr);
        	requestMap.put("platformId", request.getPlatformId());
        	requestMap.put("txStatus", "00");
        	if(numInt+1 < selectCount){
        		//如果小于总条数，查+1条
        		requestMap.put("num", numInt+1);
        		queryConfigurationInfo = payHelperUrlConfigurationMapper.queryConfigurationInfo(requestMap);
        		//记录新的redis数据
        		CacheProvider.set("num", String.valueOf(numInt+1));
        	}else{
        		//如果大于等于总条数，查第1条
        		requestMap.put("num", num);
        		queryConfigurationInfo = payHelperUrlConfigurationMapper.queryConfigurationInfo(requestMap);
        		//记录新的redis数据
        		CacheProvider.set("num", String.valueOf(0));
        	}
        }
        if(null == queryConfigurationInfo){
        	responseMap.put("success", false);
        	responseMap.put("code", BizResponseCode.URL_IS_NULL.getCode());
        	responseMap.put("message", BizResponseCode.URL_IS_NULL.getMessage());
        	return responseMap;
        }
        
        if("0".equals((String)request.getExtra().get("payStyle"))){
        	//获取动态码
        	String signStr = request.getSerialNo()+"|"+request.getOrderAmt().toString()+"|"+request.getExtra().get("payType")+"|"+queryConfigurationInfo.getNumber();
        	Map<String, Object> req = new HashMap<String, Object>();
        	req.put("number", queryConfigurationInfo.getNumber());
        	req.put("toAppParam", signStr);
        	Map<String, Object> receivablesQr = nettyFeign.getReceivablesQr(req);
        	if(BizResponseCode.OK.getCode().equals(receivablesQr.get("code"))){
        		
        		String imgbase64="\"data:image/gif;base64," + receivablesQr.get("qrCode") + "\"";
        		StringBuilder builder = new StringBuilder();
        		builder.append("<div style=\"width:100%;height:100%;text-align:center;padding-top:20px;\">");
        		builder.append("<span style=\"font-size:35px;\">￥ "+request.getOrderAmt().toString()+"</span><br>");
        		builder.append("<image ");
        		builder.append("src=" + imgbase64 + " >");
        		builder.append("</image><br>");
        		builder.append("支付即时到账，未到账请与我们联系<br>");
        		builder.append("订单号："+request.getSerialNo()+"<br>");
        		builder.append("打开");
        		if ("wechat".equals(request.getExtra().get("payType"))){
        			builder.append("微信");
        		}else if ("alipay".equals(request.getExtra().get("payType"))){
        			builder.append("支付宝");
        		}
        		builder.append("扫一扫<br>");
        		builder.append("</div>");
        		
        		resultMap.put("sendGet", builder.toString());
        		responseMap.put("outNumber", queryConfigurationInfo.getNumber());
        		responseMap.put("id", String.valueOf(queryConfigurationInfo.getId()));
        		responseMap.put("payInfo", resultMap);
        		responseMap.put("success", true);
        		responseMap.put("code", BizResponseCode.OK.getCode());
        		responseMap.put("message", BizResponseCode.OK.getMessage());
        	}else if("500".equals(receivablesQr.get("code"))){
        		responseMap.put("success", false);
        		responseMap.put("code", BizResponseCode.SEND_DATA_FAIL.getCode());
        		responseMap.put("message", BizResponseCode.SEND_DATA_FAIL.getMessage());
        		//更新url状态为异常
        		queryConfigurationInfo.setTxStatus("01");//异常
        		payHelperUrlConfigurationMapper.updateByPrimaryKey(queryConfigurationInfo);
        	}
        }else if("1".equals((String)request.getExtra().get("payStyle"))){
        	//获取静态码
        	String accountQrStr = queryConfigurationInfo.getAccountQrStr();
        	logger.info("静态二维码。。。。。{}", accountQrStr);
        	resultMap.put("sendGet", accountQrStr);
    		responseMap.put("outNumber", queryConfigurationInfo.getNumber());
    		responseMap.put("id", String.valueOf(queryConfigurationInfo.getId()));
    		responseMap.put("payInfo", resultMap);
    		responseMap.put("success", true);
    		responseMap.put("code", BizResponseCode.OK.getCode());
    		responseMap.put("message", BizResponseCode.OK.getMessage());
        }
        
		return responseMap;
	}
	
}